<?php 
function dd($data)
{
	echo "<pre>";
	print_r($data);
	echo "</pre>";
}

/**
 * 获取排序后的分类
 * @param  [type]  $data  [description]
 * @param  integer $pid   [description]
 * @param  string  $html  [description]
 * @param  integer $level [description]
 * @return [type]         [description]
 */
function getSortedCategory($data,$pid=0,$html="|---",$level=0)
{
	$temp = array();
	foreach ($data as $k => $v) {
		if($v['pid'] == $pid){
	
			$str = str_repeat($html, $level);
			$v['html'] = $str;
			$temp[] = $v;

			$temp = array_merge($temp,getSortedCategory($data,$v['id'],'|---',$level+1));
		}
		
	}
	return $temp;
}

/**
 * 根据key，返回当前行的所有数据
 * @param  string  $key  字段key
 * @return array         当前行的所有数据
 */
function getSettingValueDataByKey($key){
	return M('setting')->getByKey($key);
}

/**
 * 根据key返回field字段
 * @param  string $key   [description]
 * @param  string $field [description]
 * @return string        [description]
 */
function getSettingValueFieldByKey($key,$field){
	return M('setting')->getFieldByKey($key,$field);
}

function ajax_return( $code = 0 , $msg = 'ok' , $list =[] , $extend =[] )
{
	return json_encode(array(
		'code'=>$code,
		'msg'=>$msg,
		'list'=>$list,
		'extend'=>$extend
	));
}

function tp_return( $code = 0 , $msg = 'ok' , $list =[] , $extend =[] )
{
	return array(
		'code'=>$code,
		'msg'=>$msg,
		'list'=>$list,
		'extend'=>$extend
	);
}

/**
 * [阿里大鱼短信发送]
 * @return [type] [description]
 */
function send_sms_aldy( $phone , $code='' ){
	if(preg_match("/^1[34578]\d{9}$/", $mobile)){
		return tp_return( 1101 , '手机号码不合法' );
	}
	$api_url = C('alidayu.api_url');
	$accessKeyId = C('alidayu.access_key_id');
	$accessSecret = C('alidayu.access_secret');
	$cutime = time();
	date_default_timezone_set('GMT');
	$df = date("Y-m-d",$cutime).'T'.date("H:i:s",$cutime).'Z';
	$param['SignatureMethod'] = "HMAC-SHA1";
	$param['SignatureNonce'] = createUUid();
	$param['AccessKeyId'] = $accessKeyId;
	$param['SignatureVersion'] = "1.0";
	$param['Timestamp'] = $df;
	$param['Format'] = "JSON";
	
	$param['Action'] = "SendSms";
	$param['Version'] = C('alidayu.version');
	$param['RegionId'] = "cn-hangzhou";
	$param['PhoneNumbers'] = $phone;
	$param['SignName'] = C('alidayu.sign_name');
	if($code){
		//验证码模板
		$param['TemplateCode'] = 'SMS_116592931';//C('alidayu.register_tpl.code');
		$param['TemplateParam'] = "{\"code\":\"$code\"}";//C('alidayu.register_tpl.param');
	}else{
		//短信推送模板
		$param['TemplateCode'] = 'SMS_116592931';
	}

	ksort($param);
	$url = http_build_query($param);
	$ture_url = $url;
	$prefix = "GET&".urlencode("/")."&";
	$finalfix = speacialChar($url);
	$new_url = $prefix.$finalfix;
	$signature = urlencode($hmac_sha1_str);  
	$signature = base64_encode(hash_hmac('sha1', $new_url, $accessSecret.'&', true));
	$signature = speacialChar($signature);
	$url = $api_url.'?Signature='.$signature.'&'.$ture_url;
	$ret = curl_get($url);
	if($ret['Code']=='OK'){
		return tp_return( 0 , '发送成功' );
	}else{
		return tp_return( 1 , $ret['Message'] );
	}
}

/**
 * [createUUid description]
 * @return [type] [description]
 */
function createUUid()
{
	if (function_exists ( 'com_create_guid' )) {
		return com_create_guid ();
	} else {
		mt_srand ( ( double ) microtime () * 10000 ); 
		$charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间（微秒计）生成唯一id.
		$hyphen = chr ( 45 ); // "-"
		$uuid = '' . //chr(123)// "{"
		substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );
		//.chr(125);// "}"
		return $uuid;
	}
}

/**
 * [speacialChar description]
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function speacialChar($str)
{
	$str = urlencode($str);
	// $str = str_replace("+","%20",$str);
	// $str = str_replace("*","%2A",$str);
	// $str = str_replace("~","%7E",$str);
	return $str;
}

/**
 * [curl_get description]
 * @param  [type] $url [description]
 * @return [type]      [description]
 */
function curl_get($url)
{
	$curl = curl_init();
	curl_setopt ( $curl, CURLOPT_URL, $url );
  	curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
 	curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
 	curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
 	$output = curl_exec ( $curl );
 	if(curl_errno($curl)){
 	    echo 'Curl error: ' . curl_error($curl);
  	    exit;
  	}
 	curl_close ( $curl );
 	$ret = json_decode($output,true);
 	return $ret;
}

function getNonceStr($length = 32) 
{
	$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
	$str ="";
	for ( $i = 0; $i < $length; $i++ )  {  
		$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
	} 
	return $str;
}